- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathHashMap.rs
47 lines (40 loc) · 1.09 KB
/
HashMap.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::collections::HashMap;
structFreqStack{
num_freq:HashMap<i32,i32>,
freq_stack:HashMap<i32,Vec<i32>>,
max_freq:i32,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
implFreqStack{
fnnew() -> Self{
Self{
num_freq:HashMap::new(),
freq_stack:HashMap::new(),
max_freq:0,
}
}
fnpush(&mutself,x:i32){
let freq = self.num_freq.entry(x).or_default();
*freq += 1;
self.freq_stack.entry(*freq).or_default().push(x);
self.max_freq = self.max_freq.max(*freq);
}
fnpop(&mutself) -> i32{
let stack = self.freq_stack.get_mut(&self.max_freq).unwrap();
let x = stack.pop().unwrap();
*self.num_freq.get_mut(&x).unwrap() -= 1;
if stack.is_empty(){
self.max_freq -= 1;
}
x
}
}
/**
* Your FreqStack object will be instantiated and called as such:
* let obj = FreqStack::new();
* obj.push(x);
* let ret_2: i32 = obj.pop();
*/